<!--必要的组件说明-->
<!-- -->
<!-- author:yewenjie. date:2024/4/19 10:51-->
<template>
  <div class='quick_edit'>
    <div class="top_title">
      <div
        class="top_title_back"
        @click="$router.go(-1)"
      ><i class="iconfont icon-back"></i></div>
      <div class="top_title_val">
        {{ $route.meta.title }}
      </div>
    </div>
<!--    <van-nav-bar
      :title="$route.meta.title"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    />-->
    <div class='formBody'>
      <div class='uploadFile'>
        <div>
          <van-uploader
            @click-upload="wxUploadImg('1')"
            readonly
            v-model="fileList1"
            preview-size='140px'
            :max-count="1"
          />
          <div class="fontStyle">
            <span class='must'>车辆损失照</span>
          </div>
        </div>
        <div>
          <van-uploader
            @click-upload="wxUploadImg('2')"
            readonly
            v-model="fileList2"
            preview-size='140px'
            :max-count="1"
          />
          <div class="fontStyle">
            <span class='must'>人车合影照</span>
          </div>
        </div>
      </div>
      <div style='margin-top: 14px;display: inline-block'>
        <van-uploader
          @click-upload="wxUploadImg('3')"
          readonly
          v-model="fileList3"
          :max-count="2"
        />
        <div class="fontStyle">
          <span>其他</span>
          <img @click='()=>{tipShow = !tipShow}' src="../../assets/images/tip.png" class="tipsImg" alt="">
        </div>
      </div>
      <div v-show='tipShow' style='font-size: 14px;color: #bbbbbb;margin-top: 5px;margin-bottom: 34px'>拍摄带有车牌的照片系统将自动识别车牌号码</div>
      <van-field
        readonly
        v-model="dataSource.createTime"
        name="登记时间"
        label="登记时间"
        placeholder="登记时间"
        input-align="right"
        label-width='5em'
      />
      <van-field
        readonly
        v-model="dataSource.accidentAddress"
        name="登记地点"
        label="登记地点"
        placeholder="登记地点"
        input-align="right"
        right-icon="aim"
        rows="1"
        autosize
        type="textarea"
        label-width='5em'
        @click-right-icon='jsdkConfig()'
      />
      <div id="container"></div>
    </div>

    <div
      class="addBtn"
    >
      <van-button round type="info" @click="quickSave('save')">保存草稿</van-button>
      <van-button round type="info" @click="quickSave('next')">下一步</van-button>
    </div>

    <div class="loading" v-if="loading">
      <van-loading size="40px" class="loadbox" color="#fff" text-color="#fff">
        提交中，请稍等...
      </van-loading>
      <div class="mask"></div>
    </div>

    <van-popup v-model="showTimerPicker" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="datetime"
        @confirm="onConfirm($event, 'createTime')"
        @cancel="showTimerPicker = false"
        :formatter="formatter"
      />
    </van-popup>

  </div>
</template>

<script>
import axios from 'axios'
import qs from 'qs'
const base_url = process.env.BASE_API;
const map_url = process.env.MAP_URL

import repairApi from "@/api/repairApi";
import { getCookies, getCurrentTime_new } from '@/utils/util.js'
import { Notify } from 'vant'
import $ from 'jquery'

export default {
  name: 'quick_edit',
  components: {},
  data() {
    return {
      fileList1: [
        // { url: 'https://img01.yzcdn.cn/vant/leaf.jpg' },
      ],//车辆损失照
      fileList2: [
        // {url: 'https://img01.yzcdn.cn/vant/cat.jpeg'},
      ],//人车合影照
      fileList3: [
        // { url: 'https://img01.yzcdn.cn/vant/leaf.jpg' },
      ],//其他
      dataSource: {
        // id: '',
        // createTime: getCurrentDetailTime(),
        // accidentAddress: '厦门市集美区集美北大道华侨大学北门',
        // latitude: 24.496074,
        // longitude: 118.202965,
        id: '',
        createTime: getCurrentTime_new(),
        accidentAddress: '',
        latitude: 24.496074,
        longitude: 118.202965,
      },
      tipShow: false,
      showTimerPicker: false,
      currentDate: new Date(),
      map: null,
      loading: false
    }
  },
  methods: {
    // 保存草稿
    quickSave(tag){
      if (this.fileList1.length === 0) {
        Notify({ type: "danger", message: "请上传车辆损失照片" });
        return;
      }
      if (this.fileList2.length === 0) {
        Notify({ type: "danger", message: "请上传人车合影照片" });
        return;
      }
      if (!this.dataSource.accidentAddress) {
        Notify({ type: "danger", message: "请输入登记地点" });
        return;
      }
      if (!this.dataSource.latitude || !this.dataSource.longitude) {
        Notify({ type: "danger", message: "获取位置信息有误,请联系管理员" });
        return;
      }
      this.loading = true;
      let formData = new FormData();
      formData.append("jsonObj", JSON.stringify(this.dataSource));
      formData.append("carDamage", this.fileList1[0].file);
      formData.append("carPerson", this.fileList2[0].file);
      if (this.fileList3.length > 0) {
        this.fileList3.forEach((item) => {
          formData.append("otherPic", item.file);
        })
      } else {
        formData.append("otherPicNull", '1');
      }

      repairApi.quickAddUpdate(formData).then((res) => {
        console.info('新增/更新返回：',res)
        this.loading = false;
        if(res && res.errorCode === '-1'){
          Notify({ type: 'danger', message: res.errorMessage })
        } else {
          if(tag === 'save'){
            Notify({ type: "success", message: "添加成功" });
            this.$router.replace("/draftList");
          }else {
            this.$router.replace({
              path: "/registerEditV2",
              query: {
                id: res,
                isDetail: 0
              }
            })
          }
        }

      })

    },
    // 图片上传
    wxUploadImg(tag) {
      let vm = this
      axios({
        url: `${base_url}/proxy/qywx/jsdkConfig`,
        method: 'post',
        data: qs.stringify(
          // { url: 'http://bkt.autocnd.com' },
          { url: location.href.split('#')[0] },
          { encode: false }
        ),
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          satoken: getCookies('token'),
        },
      }).then((res) => {
        console.log('jsdkConfig:', res)
        let jsdk = res.data.data
        localStorage.setItem('jsdk', JSON.stringify(res.data.data))
        wx.config({
          beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: jsdk.corpid, // 必填，企业微信的corpID，必须是本企业的corpID，不允许跨企业使用
          timestamp: jsdk.timestamp, // 必填，生成签名的时间戳
          nonceStr: jsdk.nonceStr, // 必填，生成签名的随机串
          signature: jsdk.signature, // 必填，签名，见 附录-JS-SDK使用权限签名算法
          jsApiList: ['chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'compressImage'], // 必填，需要使用的JS接口列表，凡是要调用的接口都需要传进来
        })
        wx.ready(function (res) {
          wx.checkJsApi({
            jsApiList: ['chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'compressImage'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
            success: function (res) {
              console.log(res, '成功')
              wx.chooseImage({
                count: 1, // 默认9
                sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
                camera: {
                  mode: 'normal'
                },
                isSaveToAlbum: 1,
                success: function (res) {
                  // 多图上传遍历
                  res.localIds.forEach((item, index) => {
                    wx.getLocalImgData({
                      localId: item, // 图片的localID
                      success: function (resp) {
                        var localData = resp.localData // localData是图片的base64数据，可以用img标签显示
                        console.info(resp)
                        // vm.imgdata = resp.localData
                        vm['fileList'+tag].push({
                          url: resp.localData,
                          file: vm.base64ToFile(resp.localData, `现场照片${index}`),
                        })
                      },
                    })
                  })
                },
                fail: function (res) {
                  console.log('失败')
                },
              })
            },
            fail(err) {
              console.log(err, '失败')
            },
            complete(opt) {
              console.log(opt, '完成')
            },
          })
        })
      })
    },

    // base转换file
    base64ToFile(base64, fileName) {
      // 将base64按照 , 进行分割 将前缀  与后续内容分隔开
      let data = base64.split(",");
      // 利用正则表达式 从前缀中获取图片的类型信息（image/png、image/jpeg、image/webp等）
      let type = data[0].match(/:(.*?);/)[1];
      // 从图片的类型信息中 获取具体的文件格式后缀（png、jpeg、webp）
      let suffix = type.split("/")[1];
      // 使用atob()对base64数据进行解码  结果是一个文件数据流 以字符串的格式输出
      const bstr = window.atob(data[1]);
      // 获取解码结果字符串的长度
      let n = bstr.length;
      // 根据解码结果字符串的长度创建一个等长的整形数字数组
      // 但在创建时 所有元素初始值都为 0
      const u8arr = new Uint8Array(n);
      // 将整形数组的每个元素填充为解码结果字符串对应位置字符的UTF-16 编码单元
      while (n--) {
        // charCodeAt()：获取给定索引处字符对应的 UTF-16 代码单元
        u8arr[n] = bstr.charCodeAt(n);
      }
      // 利用构造函数创建File文件对象
      // new File(bits, name, options)
      const file = new File([u8arr], `${fileName}.${suffix}`, {
        type: type,
      });
      // 将File文件对象返回给方法的调用者
      return file;
    },

    // 获取详情
    getDetail(id){
      repairApi.getDraft({ id }).then((res) => {
        console.info(res)
        this.dataSource.accidentAddress = res.accidentAddress
        this.dataSource.createTime = res.createTime
        this.dataSource.longitude = res.longitude
        this.dataSource.latitude = res.latitude
        res.files.map(item=>{
          this['fileList'+ (item.fileType + 1)].push({url:item.fileUrl})
        })
        this.map.setCenter(new TMap.LatLng(this.dataSource.latitude, this.dataSource.longitude));

      })
    },

    // 地图获取
    jsdkConfig() {
      let vm = this;
      axios({
        url: `${base_url}/proxy/qywx/jsdkConfig`,
        method: "post",
        data: qs.stringify(
          // { url: 'http://bkt.autocnd.com' },
          { url: location.href.split("#")[0] },
          { encode: false }
        ),
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          satoken: getCookies("token"),
        },
      }).then((res) => {
        console.log("jsdkConfig:", res);
        let jsdk = res.data.data;
        localStorage.setItem("jsdk", JSON.stringify(res.data.data));
        wx.config({
          beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: jsdk.corpid, // 必填，企业微信的corpID，必须是本企业的corpID，不允许跨企业使用
          timestamp: jsdk.timestamp, // 必填，生成签名的时间戳
          nonceStr: jsdk.nonceStr, // 必填，生成签名的随机串
          signature: jsdk.signature, // 必填，签名，见 附录-JS-SDK使用权限签名算法
          jsApiList: [
            "openLocation",
            "getLocation",
            "chooseImage",
            "previewImage",
            "uploadImage",
            "downloadImage",
          ], // 必填，需要使用的JS接口列表，凡是要调用的接口都需要传进来
        });
        wx.ready(function (res) {
          wx.checkJsApi({
            jsApiList: [
              "openLocation",
              "getLocation",
              "chooseImage",
              "previewImage",
              "uploadImage",
              "downloadImage",
            ], // 需要检测的JS接口列表，所有JS接口列表见附录2,
            success: function (res) {
              console.log(res, "成功");
              wx.getLocation({
                type: "gcj02",
                success: function (res) {
                  console.log("获取用户位置信息成功：", res);
                  vm.dataSource.latitude = res.latitude; // 纬度
                  vm.dataSource.longitude = res.longitude; // 纬度
                  vm.txMap(res.latitude, res.longitude);
                },
                fail: function (res) {
                  console.log("获取用户位置信息失败！", res);
                },
              });
            },
            fail(err) {
              console.log(err, "失败");
            },
            complete(opt) {
              console.log(opt, "完成");
            },
          });
        });
      });
    },

    // 腾讯地图
    txMap(lat, lng) {
      let vm = this;
      const geolocation = new window.qq.maps.Geolocation(
        "4HEBZ-22MKH-OTBDM-WPN3E-HFCA2-ALB4C",
        "bkt_wx"
      );
      geolocation.getLocation((postion) => {
        console.log("腾讯地图获取的位置信息：", postion);
        if (postion.addr) {
          // console.log(console.log("详细获取位置：", postion));
          // vm.dataSource.accidentAddress = postion.addr;
        } else {
          // console.log(console.log("详细获取不到，通过ip类型获取", postion));
          // vm.dataSource.accidentAddress = postion.province + postion.city;
        }
      });
      this.map.setCenter(new TMap.LatLng(lat, lng));
      this.formatMap(lat, lng);
      //定义map变量，调用 TMap.Map() 构造函数创建地图
      // this.map = new TMap.Map(document.getElementById('container'), {
      //   center: new TMap.LatLng(lat, lng), //设置地图中心点坐标
      //   zoom: 17.2, //设置地图缩放级别
      //   pitch: 30.5, //设置俯仰角
      //   rotation: 45, //设置地图旋转角度
      // })
    },
    // 逆解析
    formatMap(lat, lng) {
      let vm = this;
      var data = {
        // location: "24.48405,118.03394",
        location: `${lat},${lng}`,
        /*换成自己申请的key*/
        key: "4HEBZ-22MKH-OTBDM-WPN3E-HFCA2-ALB4C",
        get_poi: 0,
      };
      var url = map_url
      data.output = "jsonp";

      $.ajax({
        type: "get",
        dataType: "jsonp",
        data: data,
        jsonp: "callback",
        jsonpCallback: "QQmap",
        url: url,
        success: function (json) {
          console.log("腾讯地图逆解析的地址：", json);
          if (json && json.result) {
            vm.dataSource.accidentAddress = json.result.address;
          }
        },
      });
    },

    onConfirm(val, field) {
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      let hour = val.getHours();
      let minute = val.getMinutes();
      // let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`;
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`;
      }
      // if (second >= 0 && second <= 9) { second = `0${second}` }
      this.dataSource[field] = `${year}-${month}-${day} ${hour}:${minute}:00`;
      this.showTimerPicker = false;
    },

    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      } else if (type === "hour") {
        return `${value}时`;
      } else if (type === "minute") {
        return `${value}分`;
      } else if (type === "second") {
        return `${value}秒`;
      }
      return value;
    },
  },
  filters: {},
  computed: {},
  props: [],
  watch: {},
  created() {
  },
  mounted() {
    let center = new TMap.LatLng(this.dataSource.latitude, this.dataSource.longitude)
    this.map = new TMap.Map(document.getElementById('container'), {
      center: center, //设置地图中心点坐标
      zoom: 17.2, //设置地图缩放级别
      pitch: 30.5, //设置俯仰角
      rotation: 45, //设置地图旋转角度
    })
    if (this.$route.query && this.$route.query.id) {
      this.getDetail(this.$route.query.id)
      this.dataSource.id = this.$route.query.id
    }else {
      this.jsdkConfig()
    }
  }
}
</script>

<style scoped lang='Less'>

.quick_edit {
  //width: 100%;
  height: 100%;

  .top_title {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 2;
    height: 50px;
    background: url(../../assets/images/title_bg.png) no-repeat;
    background-size: 100%;
    background-attachment: fixed;

    .top_title_back {
      position: absolute;
      left: 10px;
      line-height: 50px;
      color: #fff;
      font-size: 16px;
    }

    .top_title_val {
      text-align: center;
      line-height: 50px;
      color: #fff;
      font-weight: bold;
      font-size: 16px;
    }
  }

  .formBody {
    //margin-top: 50px;
    padding: 72px 15px 10px 15px;
    height: calc(100% - 145px);
    overflow-y: auto;
    .uploadFile {
      display: flex;
      justify-content: space-between;
    }
    /deep/ .van-uploader__upload {
      margin: 0 0 8px 0;
    }
    /deep/ .van-field__label {
      color: #646566;
      font-size: 15px;
    }
    /deep/ .van-field__control{
      color: #323233;
      font-size: 15px;
    }
    /deep/ .van-cell{
      padding: 10px 0;
    }
    /deep/ .van-cell::after{
      right: 0;
      left: 0;
    }
    .fontStyle {
      font-size: 12px;
      text-align: center;
      .tipsImg {
        width: 13px;
        height: 13px;
        vertical-align: top;
      }
    }
    .must::before {
      color: #ee0a24;
      font-size: 14px;
      content: '*';
    }
  }

  .addBtn {
    position: fixed;
    bottom: 0;
    width: 100%;
    z-index: 1;
    //text-align: center;
    background-color: white;
    height: 70px;
    //line-height: 45px;
    display: flex;
    justify-content: space-around;
    align-items: center;
    button {
      width: 159px;
      height: 42px;
      font-size: 20px;
    }
    button+button {
      //margin-left: 16px;
    }
  }

  .loading {
    position: fixed;
    width: 100%;
    height: 100%;
    .loadbox {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 11;
    }
    .mask {
      background: rgba(0, 0, 0, 0.5);
      position: fixed;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      z-index: 10;
    }
  }
}

</style>
